import router from '../../router/index'
import en from "../../i18n/lang/en";
export default {
  state:{
    tabs:JSON.parse(sessionStorage.getItem("addTab"))||[{
      name: en.menuTitle.records,
      path: '/index',
    }],//点击tabs
  },
  mutations:{
    //添加菜单tabs导航
    addTab(state,tab){

      if(tab.alone){
        tab = tab.children[0];
      }
      //判断数组第一个是否存在并且是否是首页
      if(state.tabs[0] && state.tabs[0].name!==en.menuTitle.records){
        state.tabs.unshift({
          name: en.menuTitle.records,
          path: '/index',
        })
      }
      //遍历数组总是否存在相同元素不存在则返回-1
      let result = state.tabs.findIndex((value => value.name===tab.name));
      if(result===-1){
        state.tabs.push(tab)
        router.push({path:tab.path});
      }else{
        router.push({path:tab.path});
      }
      sessionStorage.setItem("addTab",JSON.stringify(state.tabs));
    },
    //删除tabs
    removeTab (state, tab) {
      let index = state.tabs.findIndex(function (value, key) {
        return value.name === tab.name
      })
      state.tabs.splice(index, 1);
      if(router.path!==state.tabs[state.tabs.length-1].path){
        router.push({path:state.tabs[state.tabs.length-1].path});
      }
      sessionStorage.setItem("addTab", JSON.stringify(state.tabs))
    },
  },
  actions:{
    //新增tab
    addTab({commit},tab){
      commit("addTab",tab);
    },
    //删除tab
    removeTab({commit},tab){
      commit("removeTab",tab);
    },
  },
}
